/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jtwitlib;


import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.Token;
import org.scribe.oauth.OAuthService;
import org.scribe.model.*;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Switch;

/**
 *
 * @author Dave
 */
public class JTwitLib {
	private static String consumerKey = "bUBuDdGxZJW4kIHyCiTvOQ";
	private static String consumerSecret = "j1xnFI1dh3v5Qakky8bTSHs8BFggfsakEONhRqbo";
	private static String newline = System.getProperty("line.separator");
	private static boolean hasToken = false;
	private static OAuthService oauth;
	private static JSAP jsap = new JSAP();
	private static JSAPResult config;

	/**
	 * @param args the command line arguments
	 */
	public static void main(String[] args) throws JSAPException
	{
		
		jsap.registerParameter(new Switch("debug")
                        .setShortFlag('d')
                        .setLongFlag("debug"));
		jsap.registerParameter(new Switch("verbose")
                        .setShortFlag('v')
                        .setLongFlag("verbose"));
		
		config = jsap.parse(args);
		oauth = new ServiceBuilder()
                           .provider(TwitterApi.class)
                           .apiKey(consumerKey)
                           .apiSecret(consumerSecret)
                           .build();		
		Token requestToken = oauth.getRequestToken();
		
		Token accessToken = loadToken();
		if(config.getBoolean("debug") || config.getBoolean("verbose")){
			if(accessToken == null){
				System.out.println("No access token loaded. Initializing...");
			}
			else{
				System.out.println("Access token loaded from file.");
			}
		}
		if(!hasToken){
			accessToken = initializeToken(requestToken);
		}
		OAuthRequest request = new OAuthRequest(Verb.POST, "https://api.twitter.com/1/statuses/update.xml");
		request.addBodyParameter("status", args[0]);
		oauth.signRequest(accessToken, request);
		Response response = request.send();
		System.out.println(response.getBody());
	}
	
	private static void saveToken(Token accessToken){
		if(config.getBoolean("debug"))
		try
		{
			FileOutputStream fileOut = new FileOutputStream("Token.ser");
			ObjectOutputStream out = new ObjectOutputStream(fileOut);
			out.writeObject(accessToken);
			out.close();
			fileOut.close();
		}
		catch(IOException i)
		{
			i.printStackTrace();
		}
	}
	
	private static Token loadToken(){
		Token accessToken;
		try{
			FileInputStream fileIn = new FileInputStream("Token.ser");
			ObjectInputStream inObj = new ObjectInputStream(fileIn);
			accessToken = (Token)inObj.readObject();
			inObj.close();
			fileIn.close();
			hasToken = true;
			return accessToken;
			
		}
		catch (FileNotFoundException f){
			hasToken = false;
			return null;
		}
		catch (IOException ex) {
			System.err.println("Something strange happened. Please copy/paste this error message and send it to 'dave.stockinger@gmail.com'");
			System.err.println("Make sure to include your operating system!");
			
			Logger.getLogger(JTwitLib.class.getName()).log(Level.ALL, null, ex);
			System.exit(1);
		}
		catch (ClassNotFoundException ex) {
			System.err.println("Something strange happened. Please copy/paste this error message and send it to 'dave.stockinger@gmail.com'");
			System.err.println("Make sure to include your operating system!");
			
			Logger.getLogger(JTwitLib.class.getName()).log(Level.ALL, null, ex);
			System.exit(1);
		}
		return null;
	}
	
	private static Token initializeToken(Token requestToken){
		boolean desktopIsSupported = Desktop.isDesktopSupported();
		String authUrl = oauth.getAuthorizationUrl(requestToken);
		Verifier verifier = null;
		Token accessToken = null;
		boolean registrationFinished = false;
		
		System.out.println("Welcome to jTweet. This command-line tool allows you to send tweets via command-line");
		System.out.println("Due to Twitters OAuth authentification process, you need to register this application with your account.");
		System.out.println("To do this, a link will be displayed. Open this link and enter the displayed PIN.");
		System.out.println("jTweet does NOT have ANY information of your account. Only an encrypted token will be stored.");
		System.out.println("(If supported by your OS, the URL has been pasted to your clipboard.)");
		System.out.println("");
		
		if(true){
			setClipboardContent(authUrl);
			System.out.printf("Please visit this URL: %s%s", authUrl, newline);
			while (!registrationFinished){
				System.out.printf("Please insert your PIN here: ");
			
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				try {
					String s = in.readLine();
					verifier = new Verifier(s);
				}
				catch (IOException ex) {
					Logger.getLogger(JTwitLib.class.getName()).log(Level.SEVERE, null, ex);
				}
				
				try{
					accessToken = oauth.getAccessToken(requestToken, verifier);
					registrationFinished = true;
				}
				catch(RuntimeException e){
					System.err.println("The code you entered is invalid.");
					System.err.println("If this happens even though you are 100 % sure you entered correct, please send a mail to 'dave.stockinger@gmail.com'");
				}
				
			}
		}
		saveToken(accessToken);
		return accessToken;
	}
	private static void setClipboardContent(String s){
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), null);
	}
}